package com.orangelife.mobile.confirmOrder.activity;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Intent;
import android.graphics.Paint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.common.jump.CommonJumper;
import com.common.sp.UserSp;
import com.curry.android.http.HttpUtil;
import com.curry.android.util.DecimalUtil;
import com.curry.android.util.DialogHelper;
import com.curry.android.util.ImageDownloader;
import com.curry.android.util.ImageDownloader.ImageSize;
import com.curry.android.util.IntentHelper;
import com.curry.android.util.JSONHelper;
import com.curry.orangelife.mobile.R;
import com.orangelife.mobile.address.activity.MakeAddressListActivity;
import com.orangelife.mobile.app.application.ExitApplication;
import com.orangelife.mobile.common.activity.OrangeLifeBaseActivity;
import com.orangelife.mobile.common.biz.JSONRequest;
import com.orangelife.mobile.constants.Constant;
import com.orangelife.mobile.constants.ConfirmOrderURL;
import com.orangelife.mobile.pay.activity.UsersPaidActivity;
import com.orangelife.mobile.pay.biz.PaymentModule;
import com.orangelife.mobile.util.StringUtil;
import com.orangelife.mobile.util.ToastHelper;
import com.orangelife.mobile.voucher.biz.VoucherBiz;

import java.util.HashMap;
import java.util.Map;

/** 团购商品的提交订单界面 add this word by wgf */
public class GoodsConfirmOrderActivity extends OrangeLifeBaseActivity
        implements OnClickListener {

    /** 标题 */
    private TextView tvTitle;
    /** 商品名称 */
    private TextView tvGoodsName;
    /** 商品标题 */
//	private TextView tvGoodsTitle;
    /** 单价 */
    private TextView tvUnitPrice;
    /** 减按钮 */
    private ImageView ivMinus;
    /** 商品信息图片 */
    private ImageView ivGoods;
    /** 数量 */
    private TextView tvNumber;
    /** 加按钮 */
    private ImageView ivAdd;
    /** 总价 */
    private TextView tvTotalPrice;
    /** 抵用券信息 */
    private TextView tvVoucherInfo;
    /** 总价 */
    private TextView tvPayPrice;
    /** 底部抵用券 */
    private TextView tvPayVoucher;
    /** 底部支付 */
    private TextView tvPay;
    /** 姓名 */
    private TextView tvName;
    /** 电话 */
    private TextView tvPhone;
    /** 地址 */
    private TextView tvAddress;
    /** 邮费 */
    private TextView tvPostage;
    /** 规格 */
    private TextView tvSpecsName;
    /** 数量 */
    private TextView tvTotalNumber;
    /** 地址 */
    private LinearLayout llAddress;
    private TextView tvTitleRight;
    /** 抵用券linearlayout */
    private LinearLayout llVoucher;
    private LinearLayout llNumber;
    /** 邮费 */
    private LinearLayout llPostage;
    /** 接收从后台传来的数据 */
    private Map<String, Object> mapDetail;
    private Dialog dialog;
    private static final int GOODS_PAID = 0;
    private static final int CREDIT_PAID = 2;
    private int number = 1;
    private String money;
    private String totalPrice;
    @SuppressWarnings("unused")
    private String surplusPrice;
    private Map<String, Object> map;
    private Map<String, Object> mapPaid;
    /** 抵用券金额 */
    private Double voucher = 0.0;
    private String isAccessToken = "";
    private ImageDownloader image = ImageDownloader.getImageDownloader();
    private int limits = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_goods_comfirm_order);
        initeView();
        findView();
        setDetail();
    }

    /**
     * 初始化
     */
    private void initeView() {
        tvTitle = (TextView) findViewById(R.id.tv_title);
        tvTitleRight = (TextView) findViewById(R.id.tv_title_right);
        tvGoodsName = (TextView) findViewById(R.id.tvGoodsName);
        tvUnitPrice = (TextView) findViewById(R.id.tvUnitPrice);
        ivMinus = (ImageView) findViewById(R.id.ivMinus);
        tvNumber = (TextView) findViewById(R.id.tvNumber);
        ivAdd = (ImageView) findViewById(R.id.ivAdd);
        ivGoods = (ImageView) findViewById(R.id.ivGoods);
        tvTotalPrice = (TextView) findViewById(R.id.tvMarkerPrice);
        tvSpecsName = (TextView) findViewById(R.id.tvSpecsName);
        tvTotalNumber = (TextView) findViewById(R.id.tvTotalNumber);
        llAddress = (LinearLayout) findViewById(R.id.llAddAddress);
        llVoucher = (LinearLayout) findViewById(R.id.llVoucher);
        llNumber = (LinearLayout) findViewById(R.id.llNumber);
        llPostage = (LinearLayout) findViewById(R.id.llPostage);
        tvVoucherInfo = (TextView) findViewById(R.id.tvVoucherInfo);
        tvPayPrice = (TextView) findViewById(R.id.tvPayPrice);
        tvPayVoucher = (TextView) findViewById(R.id.tvPayVoucher);
        tvPay = (TextView) findViewById(R.id.tvPay);
        tvName = (TextView) findViewById(R.id.tv_username);
        tvPhone = (TextView) findViewById(R.id.tv_userphone);
        tvAddress = (TextView) findViewById(R.id.tv_address);
        tvPostage = (TextView) findViewById(R.id.tvPostage);
        tvPay.setOnClickListener(this);
        tvTitleRight.setVisibility(View.GONE);
    }

    /**
     * 赋值
     */
    private void findView() {
        tvTitle.setText("确认订单");
        ivAdd.setOnClickListener(listener);
        ivMinus.setOnClickListener(listener);
        llVoucher.setOnClickListener(listener);
        llAddress.setOnClickListener(listener);
        getOrderDetail();
    }

    /**
     * 设置详情
     */
    @SuppressWarnings("unchecked")
    @SuppressLint("ResourceAsColor")
    private void setDetail() {
        Intent it = getIntent();
        map = (Map<String, Object>) it
                .getSerializableExtra("map");
        if (map == null) {
            return;
        }
        try {
            number = Integer.parseInt(String.valueOf(map.get("orderNumber")));
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
        if ((Boolean) map.get("isScore")) {
            money = map.get("score").toString();
            llVoucher.setVisibility(View.GONE);
            llPostage.setVisibility(View.GONE);
            tvTotalPrice.setVisibility(View.GONE);
            tvUnitPrice.setText(money + "积分");
            tvNumber.setText(map.get("orderNumber").toString());
            tvPayPrice.setText(DecimalUtil.multiply("" + number, money) + "积分");
            image.download(map.get("goodsLogo").toString().trim(),
                    ivGoods,
                    ImageSize.IMAGE_SIZE_EXTRA_SMALL_RECTANGLE_JPG);
            tvSpecsName.setText(map.get("pdtDesc").toString());
        } else {
            /**判断是否是团购(3是团购，隐藏抵用券)*/
            if (map.get("active").toString().equals("3")) {
                limits = Integer.parseInt(String.valueOf(map.get("limits")));
                llVoucher.setVisibility(View.GONE);
            } else {
                llVoucher.setVisibility(View.VISIBLE);
                llNumber.setVisibility(View.VISIBLE);
            }
            tvVoucherInfo.setVisibility(View.VISIBLE);
            money = String.valueOf(map.get("totalPrice"));
            Intent intent = getIntent();
            String voucher = intent.getStringExtra("voucher");
            if (!StringUtil.isBlank(voucher)) {
                String voucherInfo = voucher + "元抵用券";
                VoucherBiz.setVoucherInfoBackground(tvVoucherInfo, voucherInfo, this);
            }
            tvNumber.setText(String.valueOf(map.get("orderNumber")));
            tvPayPrice.setText(Constant.RMB_FLAG + DecimalUtil.add(DecimalUtil.multiply("" + number, money), String.valueOf(map.get("shipCost"))));
            tvTotalPrice.setText(Constant.RMB_FLAG + String.valueOf(map.get("mkPrice")));
            tvUnitPrice.setText(Constant.RMB_FLAG + String.valueOf(map.get("totalPrice")));
            tvTotalPrice.getPaint().setFlags(
                    Paint.STRIKE_THRU_TEXT_FLAG);
            image.download(String.valueOf(map.get("goodsLogo")).trim(),
                    ivGoods,
                    ImageSize.IMAGE_SIZE_EXTRA_SMALL_RECTANGLE_JPG);
            tvSpecsName.setText(String.valueOf(map.get("pdtDesc")));
            tvTotalNumber.setVisibility(View.GONE);
            tvTotalNumber.setText("数量" + String.valueOf(map.get("orderNumber")));
            /**邮费为0*/
            if (Double.parseDouble(String.valueOf(map.get("shipCost"))) > 0) {
                tvPostage.setText(Constant.RMB_FLAG + String.valueOf(map.get("shipCost")));
            } else {
                tvPostage.setText("免邮");
            }
        }
        totalPrice = DecimalUtil.multiply("" + number, money);
        surplusPrice = DecimalUtil.multiply("" + number, money);
        try {
            number = Integer.parseInt(String.valueOf(map.get("orderNumber")));
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
        tvGoodsName.setText(String.valueOf(map.get("title")));
    }

    /**
     * 监听器
     */
    private OnClickListener listener = new OnClickListener() {

        @Override
        public void onClick(View view) {

            String unitPrice = money;
            switch (view.getId()) {
                case R.id.llAddAddress:
                    if (!StringUtil.isContainBlank(UserSp.getLoginID())) {
                        getAccessToken();
                    } else {
                        ToastHelper.getInstance()._toast("请先登录");
                        CommonJumper.jumpToLoginWhenExitWithClear(GoodsConfirmOrderActivity.this);
                    }
                    break;
                case R.id.ivMinus:
                    number = Integer.parseInt(tvNumber.getText().toString());
                    if (number > 1) {
                        number--;
                        tvNumber.setText(number + "");
                        totalPrice = DecimalUtil.multiply("" + number, unitPrice);
                        if ((Boolean) map.get("isScore")) {
                            tvPayPrice.setText(totalPrice + "积分");
                        } else {
                            if (voucher > Double.parseDouble(totalPrice))
                                tvPayPrice.setText("¥" + String.valueOf(map.get("shipCost")));
                            else
                                tvPayPrice.setText("¥" + DecimalUtil.add(DecimalUtil.subtract(totalPrice, voucher + ""), String.valueOf(map.get("shipCost"))));
                        }
                    }
                    break;
                case R.id.ivAdd:
                    number = Integer.parseInt(tvNumber.getText().toString());
                    if (String.valueOf(map.get("active")).equals("3")) {
                        if (number < limits) {
                            number++;
                        } else {
                            ToastHelper.getInstance()._toast("该商品已达到购买上限要求");
                        }
                    } else {
                        number++;
                    }
                    tvNumber.setText(number + "");
                    totalPrice = DecimalUtil.multiply(unitPrice, number + "");
                    if ((Boolean) map.get("isScore")) {
                        tvPayPrice.setText(totalPrice + "积分");
                    } else {
                        if (voucher > Double.parseDouble(totalPrice))
                            tvPayPrice.setText("¥" + String.valueOf(map.get("shipCost")));
                        else
                            tvPayPrice.setText("¥" + DecimalUtil.add(DecimalUtil.subtract(totalPrice, voucher + ""), String.valueOf(map.get("shipCost"))));
                    }
                    break;
                case R.id.llVoucher:
                    ToastHelper.getInstance()._toast("目前暂不支持使用抵用券");
                    break;

                default:
                    break;
            }
        }
    };

    /**
     * 获得详情
     */
    @SuppressWarnings("deprecation")
    private void getOrderDetail() {
        String repairID = "";
        Intent intent = getIntent();
        repairID = intent.getStringExtra("jumpuri");
        Map<String, Object> mapSubmit = new HashMap<String, Object>();
        mapSubmit.put("{repairId}", repairID);
        Map<String, Object> rootMap = new HashMap<String, Object>();
        rootMap.put("map", mapSubmit);
        rootMap.put("url", Constant.URL_LOOKREAPIR_DETAIL);
        rootMap.put("wat", 9);
        new JSONRequest(JSONRequest.GET, rootMap, handler, HttpUtil.ACTION_URI);
    }

    /**
     * 处理返回的信息数据
     */
    @SuppressLint("HandlerLeak")
    Handler handler = new Handler() {
        @SuppressWarnings("unchecked")
        @Override
        public void handleMessage(Message msg) {
            DialogHelper.closeDialog(dialog);
            ExitApplication.getInstance().addPaidActivity(GoodsConfirmOrderActivity.this);
            Bundle bundle = new Bundle();
            if (msg.obj == null) {
                return;
            }
            switch (msg.what) {
                case 9:
//				setDetail();
                    break;
                case 1011:
                    isLogin(dialog);
                    break;
                case 500:
//					rlRegister.setVisibility(View.GONE);
                    if (String.valueOf(msg.obj).equals("2")) {
                        ExitApplication.getInstance().addPaidActivity(GoodsConfirmOrderActivity.this);
                    } else {
                        ToastHelper.getInstance()._toast(
                                String.valueOf(msg.obj));
                    }
                    break;
                case 1001:
                    ToastHelper.getInstance()._toast(
                            getResources().getString(R.string.code_1001));
                    break;
                case GOODS_PAID:
                    mapDetail = (Map<String, Object>) JSONHelper.jsonToMap(
                            String.valueOf(msg.obj)).get("entity");
                    bundle.putString("totalCost", mapDetail.get("totalCost").toString());
//				bundle.putString("money",mapDetail.get("money").toString());
                    bundle.putString("couponCost", mapDetail.get("couponCost").toString());
                    bundle.putString("outtradeno", mapDetail.get("outtradeno").toString());
//				bundle.putString("tvPayPrice", DecimalUtil.subtract(totalPrice,voucher+""));
//				bundle.putString("orderID",mapDetail.get("orderID").toString());
//				bundle.putString("orderType", mapDetail.get("orderType").toString());
                    bundle.putString("totalPrice", Constant.RMB_FLAG + mapDetail.get("totalCost").toString());
                    bundle.putString("orderInfo", mapDetail.get("orderContent").toString());
                    bundle.putString("phone", tvPhone.getText().toString());
                    bundle.putString(PaymentModule.PAID_METHOD, PaymentModule.mode[2]);
                    bundle.putString("orderType", String.valueOf(mapDetail.get("orderType")));
                    bundle.putString("status", "goods");
                    Intent intent = new Intent(GoodsConfirmOrderActivity.this, UsersPaidActivity.class);
                    intent.putExtras(bundle);
                    startActivity(intent);
                    finish();
                    break;
                case CREDIT_PAID:
                    mapDetail = (Map<String, Object>) JSONHelper.jsonToMap(
                            msg.obj.toString()).get("entity");
                    bundle.putString("totalPrice", tvPayPrice.getText().toString());
                    bundle.putString("totalCost", totalPrice);
                    bundle.putString("orderInfo", tvGoodsName.getText().toString() + "X" + tvNumber.getText().toString());
                    bundle.putString("orderID", mapDetail.get("orderID").toString());
                    bundle.putString("orderType", String.valueOf(mapDetail.get("orderType")));
                    bundle.putInt("type", 6);
                    bundle.putString("status", "pays");
                    Intent creditIntent = new Intent(GoodsConfirmOrderActivity.this, UsersPaidActivity.class);
                    creditIntent.putExtras(bundle);
                    startActivity(creditIntent);
                    break;
                case Constant.WHAT_PERSONAL_GOODS_LIMIT:
                    ToastHelper.getInstance()._toast(msg.obj.toString());
                    break;
                case Constant.WHAT_ALL_GOODS_LIMIT:
                    ToastHelper.getInstance()._toast(msg.obj.toString());
                    break;
                case 13:
                    HashMap<String, Object> mapAccessToken = new HashMap<String, Object>();
                    mapAccessToken = (HashMap<String, Object>) JSONHelper.jsonToMap(
                            msg.obj.toString()).get("entity");
                    if ("true".equals(mapAccessToken.get("online"))) {
                        isAccessToken = "true";
                    } else {
                        isAccessToken = "false";
                    }
                    if ("true".equals(isAccessToken)) {
                        IntentHelper.getInstances().getIntent(GoodsConfirmOrderActivity.this, MakeAddressListActivity.class);
                    } else if ("false".equals(isAccessToken)) {
                        ToastHelper.getInstance()._toast("请先登录");
                        CommonJumper.jumpToLoginWhenExitWithClear(GoodsConfirmOrderActivity.this);
                    }
                    break;
                default:
                    break;
            }
        }
    };


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tvPay:
                dialog = DialogHelper.getInstance().createLoadingDialog(
                        GoodsConfirmOrderActivity.this, Constant.LOADING);
                dialog.show();
                mapPaid = new HashMap<>();
                mapPaid.put("sellPloyID", map.get("sellPloyID").toString());
                mapPaid.put("productID", map.get("productID").toString());
//                mapPaid.put("couponID", );
                mapPaid.put("orderNumber", number + "");
                mapPaid.put("shipPhone", tvPhone.getText().toString());
                mapPaid.put("shipName", tvName.getText().toString());
                mapPaid.put("shipAddr", tvAddress.getText().toString());
                String url = "";
                if ((Boolean) map.get("isScore")) {
                    url = ConfirmOrderURL.CREDIT_CONFIRM_ORDER;
                    JSONRequest.getInstance().sendRequest(JSONRequest.POST, url, mapPaid, handler, CREDIT_PAID, HttpUtil.ACTION_JSON);
                } else {
                    if (map.get("active").toString().equals("1")) {/**商品*/
                        url = ConfirmOrderURL.GOODS_CONFIRM_ORDER;
                    } else if (map.get("active").toString().equals("2")) {
                        url = ConfirmOrderURL.UNDERLINE_ADD;
                    } else if (map.get("active").toString().equals("3")) {/**团购*/
                        mapPaid.put("actvtID", map.get("actvtID"));
                        url = ConfirmOrderURL.GROUP_ADD;
                    }
                    JSONRequest.getInstance().sendRequest(JSONRequest.POST, url, mapPaid, handler, GOODS_PAID, HttpUtil.ACTION_JSON);
                }
                break;
            default:
                break;
        }

    }

    @SuppressWarnings("unchecked")
    @SuppressLint("ResourceAsColor")
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
    }


    /**
     * 获取用户会话登录状态
     */
    private void getAccessToken() {
        Map<String, Object> map = new HashMap<>();
        map.put("{accessToken}", UserSp.getAccessToken());
        JSONRequest.getInstance().sendRequest(JSONRequest.GET, Constant.URL_ACCESSTOKEN, map, handler, 13, HttpUtil.ACTION_URI);
    }
}

